<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <div class="discharge-application">
        <h1>退住申请</h1>
        <el-form :model="applicationData" ref="form" label-width="120px">
          <el-form-item label="住户姓名" prop="residentName" :rules="[{ required: true, message: '请输入住户姓名', trigger: 'blur' }]">
            <el-input v-model="applicationData.residentName" />
          </el-form-item>
          <el-form-item label="退住原因" prop="reason" :rules="[{ required: true, message: '请输入退住原因', trigger: 'blur' }]">
            <el-input type="textarea" v-model="applicationData.reason" />
          </el-form-item>
          <el-form-item label="申请日期" prop="date" :rules="[{ required: true, message: '请选择申请日期', trigger: 'change' }]">
            <el-date-picker v-model="applicationData.date" type="date" placeholder="选择日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitApplication">提交申请</el-button>
          </el-form-item>
        </el-form>
        <p v-if="errorMessage" class="error">{{ errorMessage }}</p> <!-- 错误信息 -->
        <h2>申请记录</h2>
        <el-table :data="applications" style="width: 100%">
          <el-table-column prop="residentName" label="住户姓名" />
          <el-table-column prop="reason" label="退住原因" />
          <el-table-column label="申请日期">
            <template v-slot="scope">
              {{ formatDate(scope.row.DATE) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="small" @click="editApplication(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteApplication(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue';
import axios from 'axios';

export default {
  name: 'DischargeApplication',
  components: {
    AsideLayout
  },
  data() {
    return {
      applicationData: {
        residentName: '',
        reason: '',
        date: new Date().toISOString().split('T')[0] // 默认为今天的日期
      },
      errorMessage: '', // 错误信息
      applications: []
    };
  },
  mounted() {
    this.fetchApplications();
  },
  methods: {
    fetchApplications() {
      axios.get('http://localhost:3000/api/discharge-applications')
        .then(response => {
          this.applications = response.data;
        })
        .catch(error => {
          console.error('Error fetching discharge applications:', error);
        });
    },
    submitApplication() {
      // 表单验证
      this.$refs.form.validate((valid) => {
        if (!valid) {
          this.errorMessage = '请填写所有字段';
          return;
        }
        this.errorMessage = ''; // 清除错误信息

        if (this.applicationData.id) {
          axios.put(`http://localhost:3000/api/discharge-applications/${this.applicationData.id}`, this.applicationData)
            .then(() => {
              this.fetchApplications();
              this.applicationData = { residentName: '', reason: '', date: new Date().toISOString().split('T')[0] };
              this.$message.success('退住申请更新成功');
            })
            .catch(error => {
              console.error('Error updating discharge application:', error);
              this.$message.error('退住申请更新失败');
            });
        } else {
          axios.post('http://localhost:3000/api/discharge-applications', this.applicationData)
            .then(() => {
              this.fetchApplications();
              this.applicationData = { residentName: '', reason: '', date: new Date().toISOString().split('T')[0] };
              this.$message.success('退住申请添加成功');
            })
            .catch(error => {
              console.error('Error adding discharge application:', error);
              this.$message.error('退住申请添加失败');
            });
        }
      });
    },
    editApplication(application) {
      this.applicationData = { ...application }; // 将选中的申请数据填入表单
    },
    deleteApplication(application) {
      this.$confirm(`确认删除退住申请 ${application.residentName} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/discharge-applications/${application.id}`)
          .then(() => {
            this.fetchApplications();
            this.$message.success('退住申请删除成功');
          })
          .catch(error => {
            console.error('Error deleting discharge application:', error);
            this.$message.error('退住申请删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    formatDate(dateString) {
      const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', options);
    }
  }
};
</script>

<style scoped>
.el-container {
  height: 100vh; /* 使容器占满整个视口高度 */
}

.discharge-application {
  padding: 30px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  flex: 1; /* 使内容区域自适应 */
}

.error {
  color: red;
  margin-top: 10px;
}
</style>